package com.ls.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.ls.blog.common.exception.CodeErrorException;
import com.ls.blog.dto.QQDTO;
import com.ls.blog.dto.UserDetailsIml;
import com.ls.blog.entity.User;
import com.ls.blog.service.RoleService;
import com.ls.blog.service.UserService;
import com.ls.blog.utils.IpUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Resource
    private HttpServletRequest httpRequest;

    @Resource
    private RestTemplate restTemplate;

    @Resource


    @Autowired
    private RoleService roleService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        //根据用户名查询用户
        UserDetailsIml userDetailsIml = userService.getUserDTOByUserName(username);
        if (userDetailsIml == null) {
            throw new RuntimeException("用户不存在");
        }
        // 获得用户信息
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //获取该用户所拥有的角色列表
        List<String> roleCodeList =  roleService.getRoleByUserId(userDetailsIml.getId());
        // 声明用户授权
        roleCodeList.forEach(roleCode -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(roleCode);
            grantedAuthorities.add(grantedAuthority);
        });
        userDetailsIml.setAuthorityList(grantedAuthorities);
        String ip = IpUtil.getIpAddr(httpRequest);
        userDetailsIml.setIp(ip);
        userDetailsIml.setAddress(IpUtil.getIpSource(ip));
      return userDetailsIml;
    }

    public UserDetailsIml getByEmail(String email) throws CodeErrorException {
        // 校验邮箱
        if (!checkEmail(email)){
            throw new CodeErrorException("邮箱格式错误");
        }
        User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, email).or().eq(User::getUsername,email));
        String ip = IpUtil.getIpAddr(httpRequest);
        if (one == null){
            one = new User();
            String s = email.split("@")[0];
            QQDTO data = new QQDTO();
            try {
                JSONObject object = restTemplate.getForObject("https://api.usuuu.com/qq/"+s, JSONObject.class);
                data = JSON.parseObject(JSONObject.toJSON(object.get("data")).toString(), QQDTO.class);
            }catch (Exception e){
                throw new CodeErrorException("邮箱格式错误");
            }
            one.setIp(ip);
            one.setUsername(s);
            one.setEmail(email);
            one.setAvatar(data.getAvatar());
            one.setNickname(data.getName());
        }
        UserDetailsIml userDetailsIml = new  UserDetailsIml();
        // 获得用户信息
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //获取该用户所拥有的角色列表
        List<String> roleCodeList =  roleService.getRoleByUserId(one.getId());
        if (roleCodeList.size()==0){
            // 没有角色填充一个默认的用户角色
            roleCodeList.add("user");
        }
        // 声明用户授权
        roleCodeList.forEach(roleCode -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(roleCode);
            grantedAuthorities.add(grantedAuthority);
        });

        BeanUtils.copyProperties(one,userDetailsIml);
        userDetailsIml.setAuthorityList(grantedAuthorities);
        userDetailsIml.setIp(ip);
        userDetailsIml.setAddress(IpUtil.getIpSource(ip));
        return userDetailsIml;
    }

    public static boolean checkEmail(String email){
        String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        return matcher.matches();
    }

    public void foreach(Function<String,String> function)  {
        throw new RuntimeException("22");
    }
}

